package com.compass.mobile.ui.activity

import UserInfoManager
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import com.compass.mobile.R
import com.compass.mobile.callback.OnCustomButtonClick
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.ActivityPatientsBinding
import com.compass.mobile.framework.base.BaseVBActivity
import com.compass.mobile.framework.constant.ADD_PATIENT
import com.compass.mobile.framework.constant.LOCAL_PHONE
import com.compass.mobile.framework.constant.PATIENT_SWITCH
import com.compass.mobile.framework.constant.REFRESH_PATIENT
import com.compass.mobile.framework.constant.YD_USER_ID
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.utils.LiveDataBus
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.PatientBean
import com.compass.mobile.presenters.PatientPresenter
import com.compass.mobile.ui.dialog.AddPatientTipsDialog
import com.compass.mobile.ui.dialog.CodeDialog
import com.compass.mobile.ui.dialog.CommonMessageDialog
import com.compass.mobile.ui.dialog.InputPhoneDialog
import com.compass.mobile.ui.dialog.SetPatientDialog
import com.compass.mobile.ui.viewModel.UserViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import getStringFromResource

/**
 * Description： 就诊人列表
 * Date:2024/6/12 11:25
 */
class PatientsActivity : BaseVBActivity<ActivityPatientsBinding>() {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, PatientsActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val userViewModel: UserViewModel by viewModels()
    private lateinit var arrayObjectAdapter: ArrayObjectAdapter
    private var patientList: MutableList<PatientBean> = mutableListOf()//包装集合
    override fun initView(savedInstanceState: Bundle?) {
        specialColumn()
        mBinding.topView.setPatientViewVisible(false)
    }

    override fun initData() {
        showLoading()
        userViewModel.gePatients()

        userViewModel.patientLiveData.observe(this) {
            it?.let { list ->
                patientList = list
                patientList.add(PatientBean("10086"))
                if (patientList.isNotEmpty()) {
                    mBinding.emptyView.gone()
                    arrayObjectAdapter.clear()
                    arrayObjectAdapter.addAll(0, patientList)
                    mBinding.caseItem.requestFocus()
                } else {
                    mBinding.emptyView.visible()
                }
            } ?: kotlin.run {
                mBinding.emptyView.visible()
            }
            dismissLoading()
        }
        userViewModel.refreshPatientLiveData.observe(this) {
            dismissLoading()
            if (it) {
                showLoading()
                userViewModel.gePatients()
                LiveDataBus.get().with(PATIENT_SWITCH).postValue(PATIENT_SWITCH)
            }
        }

        userViewModel.checkMobileLiveData.observe(this) {
            dismissLoading()
            if (it) {
                //检测已经存在则进行同步患者
                showAddPatientDialog(1)
            } else {
                //不存在
                showAddPatientDialog(2)
            }
        }


    }

    private fun showAddPatientDialog(type: Int) {
        val message =
            if (type == 1) "当前手机号已存在就诊人数据，是否导入?" else "是否使用当前手机号添加就诊人？"
        CommonMessageDialog.Builder(this)
            .setTitle("温馨提示")
            .setMessage(message)
            .setConfirm(getStringFromResource(R.string.default_confirm))

            .setCancel(getString(R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {
                it?.dismiss()

                if (type == 1) {
                    showLoading()
                    userViewModel.getMobileSync(phoneNumber, code, "2")
                } else {
                    phoneNumber?.let { it1 -> AddPatientActivity.start(this@PatientsActivity, it1) }
                }

            }.create().show()


    }

    override fun intListener() {
        mBinding.tvRefresh.onClick {
            showLoading()
            userViewModel.gePatients()
        }
        LiveDataBus.get().with(REFRESH_PATIENT).observe(this) {
            userViewModel.gePatients()
        }
    }

    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            val item = patientList[position]
            if (item.id == "10086") {
                cancelInquire()
            } else {
                CommonMessageDialog.Builder(this@PatientsActivity)
                    .setTitle("温馨提示")
                    .setMessage("是否要将当前就诊人解除绑定?")
                    .setConfirm(getStringFromResource(R.string.default_confirm))

                    .setCancel(getString(R.string.default_cancel))
                    .setonCancelListener {
                        it?.dismiss()
                    }
                    .setonConfirmListener {
                        it?.dismiss()
                        userViewModel.unbindPatients(item.id)
                    }.create().show()
//                SetPatientDialog.Builder(this@PatientsActivity)
//                    .setonCancelListener {
//                        it?.dismiss()
//                        userViewModel.switchPatients(item.id)
//                    }
//                    .setonConfirmListener {
//                        userViewModel.unbindPatients(item.id)
//                        it?.dismiss()
//                    }.create().show()
            }
        }
    }


    private var onBottomClick: OnCustomButtonClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(codeType: Int, msgType: String?) {
            when (msgType) {
                "local" -> {
//                    showLoading()
//                    userViewModel.getMobileSync("17782523372", "", "1")
                    //跳转至添加页面
                    UserInfoManager.getString(LOCAL_PHONE)?.let {
                        AddPatientActivity.start(this@PatientsActivity, it)
                    } ?: kotlin.run {
                        showToast("本机号码获取失败")
                    }


                }

                "other" -> {
                    useOther()
                }

                "code" -> {
//                    useCode()
//                    AddPatientActivity.start(this@PatientsActivity)
                }
            }
        }
    }


    /**
     * 添加就诊人弹窗
     */
    private fun cancelInquire() {
        UserInfoManager.getString(LOCAL_PHONE)?.let {
            val addPatientTipsDialog =
                AddPatientTipsDialog.Builder(this, it, onBottomClick)
            addPatientTipsDialog.show()
        } ?: kotlin.run {
            showToast("本机号码获取失败")
        }

    }


    private var phoneNumber: String? = null
    private var code: String? = null
    private var onPhoneClick: OnCustomButtonClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(codeType: Int, msgType: String?) {
            when (codeType) {
                1 -> {
                    phoneNumber = msgType
                    if (phoneNumber.isNullOrEmpty()) {
                        showToast("请输入手机号码")
                        return
                    }
                    userViewModel.getCode(phoneNumber)

                }

                2 -> {
                    code = msgType
                    if (phoneNumber.isNullOrEmpty()) {
                        showToast("请输入验证码")
                        return
                    }
                    showLoading()
                    //先调用接口检测是否有就诊人，有的话，则让用户确认 同步、创建
                    userViewModel.checkMobile(phoneNumber, code, "2")
//                    showLoading()
//                    userViewModel.getMobileSync(phoneNumber, code, "2")
                }


            }


        }
    }

    private fun useOther() {
        val inputPhoneDialog = InputPhoneDialog.Builder(this@PatientsActivity, onPhoneClick)
        inputPhoneDialog.show()
    }

    /**
     * 使用扫码
     */
    private fun useCode() {
        val oderCodeDialog = CodeDialog.Builder(
            this@PatientsActivity,
            ADD_PATIENT + UserInfoManager.getString(YD_USER_ID)
        )
        oderCodeDialog.show()
    }

    @SuppressLint("RestrictedApi")
    fun specialColumn() {
        mBinding.caseItem.horizontalSpacing = dpToPx(10)
        arrayObjectAdapter = ArrayObjectAdapter(PatientPresenter())
        val itemBridgeAdapter = MyBridgeAdapter(
            this,
            arrayObjectAdapter, onItemClickListener
        )
        mBinding.caseItem.setAdapter(itemBridgeAdapter)
        mBinding.caseItem.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
        arrayObjectAdapter.addAll(0, patientList)

        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )


    }
}
